package com.jwthhealth_pub.wristband.manager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.Context;
import android.util.Log;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 扫描附近蓝牙设备
 * 查询已经配对的设备
 * 连接蓝牙
 * Created by liuzhen on 2017/11/23.
 */

public class BLEManager {
    public static final int REQUEST_ENABLE_BT = 10;//作为蓝牙开启请求responseCode的参数

    private static final String TAG = makeLogTag(BLEManager.class);

    private Context mContext;

    private BluetoothAdapter mBluetoothAdapter;

    public BLEManager(Context mContext) throws Exception {
        this.mContext = mContext;

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null)
            throw new Exception("设备不支持蓝牙");
    }

    /**
     * 判断蓝牙是否开启
     *
     * @return boolean
     */
    public boolean isEnable() {
        if (mBluetoothAdapter == null)
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    }

    public void scan() {
        if (mBluetoothAdapter == null)
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        mBluetoothAdapter.cancelDiscovery();
        mBluetoothAdapter.startDiscovery();
    }

    public void scanCancel() {
        mBluetoothAdapter.cancelDiscovery();
    }

    public BluetoothGatt conn(BluetoothDevice mBtDevice, BluetoothGattCallback mGattCallback) {
        return mBtDevice.connectGatt(mContext, false, mGattCallback);
    }

    /**
     * 获取已经连接的蓝牙设备
     *
     * @return dev list
     */
    public List<BluetoothDevice> getConnDev() {
        final List<BluetoothDevice> deviceList = new ArrayList<>();

        if (mBluetoothAdapter == null)
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

//        方案一
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;

        try {
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Log.i(TAG, "BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                Log.i(TAG, "devices:" + devices.size());

                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) {
                        Log.i(TAG, "connected:" + device.getName());
                        deviceList.add(device);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

        //方案二
//        int a2dp = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
//        int headset = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
//        int health = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
//
//        int flag = -1;
//        if (a2dp == BluetoothProfile.STATE_CONNECTED) {
//            flag = a2dp;
//        } else if (headset == BluetoothProfile.STATE_CONNECTED) {
//            flag = headset;
//        } else if (health == BluetoothProfile.STATE_CONNECTED) {
//            flag = health;
//        }
//
//        if (flag != -1) {
//            mBluetoothAdapter.getProfileProxy(App.mContext, new BluetoothProfile.ServiceListener() {
//
//                @Override
//                public void onServiceDisconnected(int profile) {
//                    // TODO Auto-generated method stub
//
//                }
//
//                @Override
//                public void onServiceConnected(int profile, BluetoothProfile proxy) {
//                    // TODO Auto-generated method stub
//                    List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
//                    if (mDevices != null && mDevices.size() > 0) {
//                        for (BluetoothDevice device : mDevices) {
//                            Log.i(TAG, "device name: " + device.getName());
//                            deviceList.add(device);
//                        }
//                    } else {
//                        Log.i(TAG, "mDevices is null");
//                    }
//                }
//            }, flag);
//        }

        Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();

        Log.d(TAG, "bondedDevices:" + bondedDevices);

        for (BluetoothDevice device : bondedDevices) {
            Log.d(TAG, device.getName());
            Log.d(TAG, "device.getBondState():" + device.getBondState());
        }

        return deviceList;
    }
}
